// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
const _=db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let list = event.weRunData.data.stepInfoList;//31天数据列表
  let openid = wxContext.OPENID;
  let time = list[30].timestamp;//今日时间戳
  let step=Number(list[30].step);//今日步数
  let jf = Math.round(step/ 100.0);
  //检查是不是新用户
  let proCount = await db.collection('userData').where({
    openid: openid
  }).count();
  if (proCount.total != 1) {
    //如果是新用户初始历史积分和历史运动天数并加入数据库
    await db.collection('userData').add({
      data: {
        openid: openid,
        time: Number(time),
        history: 0,
        runDays: 1,
      }
    });
    return {
      step,
      jf,
      totalJf: jf,
      runDays: 1
    }
  }

  else{
    let proData = await db.collection('userData').where({
      openid: openid
    }).field({ time: true, history: true, runDays: true }).get();

    let data = proData.data;
    let timeLast = data[0].time;//上一次登录日期
    let days=(time-timeLast)/86400;
    if (time == data[0].time) {
      //如果是同天登录不更新数据库的history和runDays
      return {
        step,
        jf,
        totalJf: data[0].history + jf,
        runDays: data[0].runDays
      }
    }
    else
    {
      //不是当天登录更新history和rundays
      let hisStepInc=0; //历史步数的增量

      for(let i=29;i>=0;i--){
        //循环把历史总步数的增量算出来
        hisStepInc+=list[i].step;
        if(list[i].timestamp==timeLast){
          //加到上次登录的那一天
          break;
        }
      }
      hisJfInc=Math.round(hisStepInc/100.0);

      await db.collection('userData').where({
        openid: openid
      }).update({
        data: {
          time: time,
          history: _.inc(hisJfInc),
          runDays: _.inc(days)
        }
      })
      return {
        step,
        jf,
        totalJf: data[0].history + hisJfInc+jf,
        runDays: (data[0].runDays + days)
      }
    }
  }
}